<script setup lang="ts">
import {
  onBeforeUnmount,
  nextTick,
  onBeforeMount,
  onMounted,
  reactive,
  ref,
  inject,
} from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import getArticleCard from '@/api/getArticleCard';
import convertTime from '@/api/convertTime';
import getComments from '@/api/getComments';
import getHotNews from '@/api/getHotNews';
import { userinfo } from '@/stores/counter';
import type { Cate } from '../types/types.d.ts';
import HotArticles from '@/components/HotArticles.vue';

import Chat from '@/components/Chat.vue';
import articleStar from '@/api/articleStar';

const user = userinfo();
const { singleCard } = getArticleCard();
const { comments } = getComments();
const { getTime } = convertTime();
const { getHotList } = getHotNews();
const router = useRouter();
const hotList = ref([]);
const cates = inject('cates') as Cate[];
const { setStar, getStar } = articleStar();
onBeforeMount(() => {
  user.curArticle = '';
});
let count = 0;
router.afterEach((to, from, next) => {
  const id = to.params.id;
  if (to.name == 'article') {
    user.curArticle = '';
    singleCard(parseInt(`${id}`), true);
    comments(`${id}`);
    getCountAndStar();
  }
});


onMounted(async () => {
  window.scrollTo(0, 0);
  singleCard(parseInt(`${router.currentRoute.value.params.id}`), true);
  comments(`${router.currentRoute.value.params.id}`);
  hotList.value = await getHotList();
  getCountAndStar();
  //   updateStarStyle();
  // viewing(parseInt(router.currentRoute.value.params.id as string),1)
  // console.log(user.curArticle.Content)

});

async function getCountAndStar() {
  if (user.baseInfo.id) {
    isFav = await getStar(
      parseInt(`${router.currentRoute.value.params.id}`),
      user.baseInfo.id
    );
    updateStarStyle();
  }
  count = user.curComment.length;
  for (const item of user.curComment) {
    // console.log(item)
    // console.log(item.replies.length)
    count += item.replies.length;
  }
  
}

function goback() {
  router.go(-1);
}

function toTopics(item: any) {
  let aimId = -1;
  let name = item.slice(0, item.indexOf('议题'));
  for (let i of cates) {
    if (i.name.indexOf(name) != -1) {
      aimId = i.id;
      break;
    }
  }
  if (aimId != -1) {
    router.push('/cate/' + aimId);
  }
}

const updateStarStyle = () => {
  if (!isFav) {
    starStyle.color = isHovered.value ? '#fc6704' : '#cdcdcd';
  } else {
    starStyle.color = '#fc6704';
  }
  //   starStyle.borderColor = isHovered.value ? '#fc6704' : '#cdcdcd';
  //   console.log(starStyle.borderColor);
};

const isHovered = ref(false);
let isFav = false;
const starStyle = reactive({
  color: '#cdcdcd',
  borderColor: '#cdcdcd',
});

const startHoverAnimation = () => {
  if (!isFav) {
    isHovered.value = true;
    updateStarStyle();
  }
};

const resetAnimation = () => {
  if (!isFav) {
    isHovered.value = false;
    updateStarStyle();
  }
};

onBeforeUnmount(() => {
  resetAnimation();
});
// const isFav = ref(false);
const changeStar = async () => {
  if (!user.baseInfo.id || !user.curArticle.id) {
    ElMessage({
      showClose: true,
      message: '请先登录',
      type: 'error',
    });
    return;
  }
  if (await setStar(user.curArticle.id, user.baseInfo.id)) {
    isFav = !isFav;
    updateStarStyle();
  }
};
</script>

<template>
    <div class="article-div">
        <Chat />
        <div class="goback" @click="goback()">
            <el-icon color="#f5900a">
                <ArrowLeftBold />
            </el-icon>
        </div>
        <div class="article-sec">
            <div class="article-left">
                <el-skeleton :rows="15" animated :loading="user.curHtml == ''">
                    <template #default>
                        <div class="article-main">
                            <div class="article-title">
                                {{ user.curArticle.title }}
                            </div>
                            <div class="article-info">
                                <!-- 作者：{{ user.curArticle.author }} 时间：{{ getTime(user.curArticle.publishTime).split(' ')[0] }} -->
                                作者：{{ user.curArticle.author }} 时间：{{ user.curArticle.publishTime.split(' ')[0]}}
                            </div>
                            <!-- <div class="article-text"> -->
                            <el-skeleton :rows="15" animated :loading="user.curHtml == ''" />
                            <div v-html="user.curHtml"></div>
                            <div class="article-tail">
                                <div class="article-tag">
                                    <!-- 议题标签： -->
                                    <!-- <div v-for="item in user.curArticle.cates" class="tags" @click="toTopics(item)">
                                        {{ item }}
                                    </div> -->
                </div>
                <a class="application" :href="user.curArticle.refUrl">
                  原文链接
                </a>
              </div>
            </div>
            <div class="line"></div>
            <div class="star">
              <span
                style="color: #cdcdcd; margin-top: 50px; margin-bottom: 30px"
              >
                觉得文章不错？ 点赞支持一下！
              </span>
              <div>
                <div
                  class="star-border"
                  @mouseenter="startHoverAnimation()"
                  @mouseleave="resetAnimation()"
                  @click="changeStar()"
                >
                  <el-icon size="40px" :style="starStyle">
                    <Star />
                  </el-icon>
                </div>
              </div>
            </div>
            <div class="comment-title">
              <div class="comment-text">
                评论
                <span
                  style="color: #696969; font-size: 15px; margin-left: 10px"
                  >{{ count }}</span
                >
              </div>
              <!-- <div class="new">最新</div>
                            <div>|</div>
                            <div class="hot">最热</div> -->
            </div>
            <Postcomment
              :newsId="user.curArticle.id"
              :commentId="0"
              :replyCommentId="0"
              :fatherId="0"
            />
            <div class="comment-main">
              <Commenting
                v-for="item in user.curComment"
                :newsId="user.curArticle.id"
                :name="item.userName"
                :text="item.content"
                :time="item.createTime"
                :avatar="item.avator"
                :like="item.likeNum"
                :commentId="item.id"
                :toId="item.userId"
                :sub="item.replies"
                :isStared="item.myLike"
              />
              <div class="empty" v-if="user.curComment.length == 0">
                暂时还没有评论哦~
              </div>
            </div>
          </template>
        </el-skeleton>
      </div>
      <div class="article-right">
        <!-- <Rightcard /> -->
        <HotArticles :article-list="hotList" />
      </div>
    </div>
  </div>
</template>

<style scoped>
.star {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.star-border {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 100%;
  border: 2px #cdcdcd solid;

  transition: color 0.3s ease, border-color 0.3s ease;
}
.article-div {
  width: 100%;
}

.goback {
  width: 40px;
  height: 40px;
  background-color: white;
  box-shadow: #475669 1px 1px;
  border-radius: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 3%;
  cursor: pointer;
}

.article-sec {
  width: 1200px;
  min-width: 1200px;
  display: flex;
  align-items: start;
  /* background-color: red; */
  margin: 20px auto 0;
}

.article-left {
  /* background-color: red; */
  width: 65%;
}

.article-main {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: start;
}

.article-right {
  width: 30%;
  margin-top: 20px;
  margin-left: auto;
}

.article-title {
  font-size: 25px;
  font-weight: bold;
}

.article-info {
  font-size: 14px;
  color: #989798;
  margin: 10px 0px;
}

/* .article-text {
    line-height: 32px;
    margin-top: 15px;
    font-size: 15px;
} */

.article-tag {
  display: flex;
  height: 100%;
  color: #f8ad4e;
  font-size: 20px;
  align-items: center;
}

.tags {
  /* font-weight: 500; */
  border-radius: 30px;
  background-color: #ed823b;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  padding: 6px 10px;
  cursor: pointer;
}

.article-tail {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 15px;
}

.application {
  background-color: #fc6704;
  color: white;
  padding: 5px 18px;
  cursor: pointer;
  text-decoration: none;
}

.line {
  height: 1px;
  width: 100%;
  margin-top: 15px;
  background-color: black;
}

.comment-text {
  font-size: 22px;
}

.comment-title {
  display: flex;
  align-items: end;
  margin-top: 20px;
}

.new {
  margin-left: 20px;
  margin-right: 5px;
  cursor: pointer;
}

.hot {
  margin-left: 5px;
  cursor: pointer;
}

.empty {
  width: 100%;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 25px;
}
</style>
